package com.uxsino.commons.utils.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;

public class PropJsonObjectElement extends PropJsonElement {

    public PropJsonObjectElement(PropJsonDocument doc, JsonNode node) {
        super(doc, node);
    }

    @Override
    public String getProp(String name) {
        JsonNode valueNode = node.get(name);
        return valueNode == null ? "" : valueNode.textValue();
    }

    @Override
    public Map<String, String> getProps() {
        HashMap<String, String> props = new HashMap<>();
        Iterator<Map.Entry<String, JsonNode>> fields = node.fields();

        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> entry = fields.next();
            String nodeName = entry.getKey();
            JsonNode x = entry.getValue();
            JsonNodeType t = x.getNodeType();

            if (t != JsonNodeType.ARRAY && t != JsonNodeType.OBJECT) {
                props.put(nodeName, x.asText());
            }
        }
        return props;
    }

    @Override
    public List<PropElement> getChildElements(String childFieldName) {
        ArrayList<PropElement> list = new ArrayList<>();
        if (childFieldName == null) {
            list.add(doc.createElement(node));
        } else {
            JsonNode child = node.get(childFieldName);

            if(child != null){
                child.forEach(n -> {
                    list.add(doc.createElement(n));
                });
            }
        }
        return list;
    }

    @Override
    public List<PropElement> getElements(String name) {
        ArrayList<PropElement> list = new ArrayList<>();
        JsonNode child = node.get(name);

        if (child == null || child.getNodeType() != JsonNodeType.ARRAY) {
            return list;
        }

        child.forEach(n -> list.add(doc.createElement(n)));
        return list;
    }

    @Override
    public PropElement getFirstElement(String name, String fieldAsTag) {
        JsonNode child = node.get(name);

        if (child == null) {
            return null;
        }

        if (child.getNodeType() == JsonNodeType.ARRAY && child.size() > 0) {
            return doc.createElement(child.get(0));
        } else if (child.getNodeType() == JsonNodeType.OBJECT) {
            return doc.createElement(child);
        }
        return null;
    }

    @Override
    public String getText() {
        return node.asText();
    }

}
